package com.roger.myHome.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.roger.myHome.domain.TbUsers;
import com.roger.myHome.entity.LoginUser;
import com.roger.myHome.mapper.UsersMapper;
import com.roger.myHome.service.LoginService;
import com.roger.myHome.util.Constants;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import java.util.List;
import static com.roger.myHome.util.AESUtil.AESEncode;

@Service
public class LoginServiceImpl implements LoginService {
    @Resource
    private UsersMapper usersMapper;

    @Override
    public LoginUser loginUser(String loginName, String password) {

        QueryWrapper<TbUsers> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("password","id","username","login_name").eq("login_name",loginName);
        List<TbUsers> userList = usersMapper.selectList(queryWrapper);
        if(userList.isEmpty()){
            return null;
        }

        TbUsers info = userList.get(0);
        String dbPwd = info.getPassword();
        String AESDecodePwd = AESEncode(Constants.ENCODE, password);
        if (!dbPwd.equals(AESDecodePwd)) {
            return null;
        }

        LoginUser loginUser = new LoginUser();
        loginUser.setUsername(info.getUsername());
        loginUser.setLoginName(info.getLoginName());
        loginUser.setId(info.getId());
        return loginUser;
    }
}
